<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.camiloinventory_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-button type="primary"
          icon="el-icon-plus"
          size="small"
          plain
          @click.stop="importExcel">导入</el-button>  
      </template>   
    </avue-crud>
    <el-dialog :title="'卡密导入'"
               append-to-body
               :visible="box"
               :before-close="dialogClose">
      <!-- <avue-form :option="optionChild" v-model="formChild" @submit="handleSubmit"></avue-form> -->
      <div>
        <div style="margin-bottom:10px">
          请下载订单模板，按格式修改后导入<el-button type="text" icon="el-icon-download" style="float:right;padding:0" @click="downloadFile">点击下载</el-button>
        </div>
        <avue-form :option="optionChild" v-model="formChild" ref="uploadForm"></avue-form>
        <el-upload
          class="upload-demo"
          ref="upload"
          action="/api/merchant-bmg/camiloinventory/importExcel"
          :data="activityForm"
          :headers="header"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-success="uploadSuccess"
          :on-error="uploaderror"
          :on-change="fileChange"
          :file-list="fileList"
          :auto-upload="false"
          accept=".xls,.xlsx"
          limit="1"
          drag
          >
          <i class="el-icon-upload" style="color:#409eff"></i>
          <div class="el-upload__text"><em>上传文件</em></div>
        </el-upload>
      </div>
       <span slot="footer" class="dialog-footer">
        <el-button @click="dialogClose">取 消</el-button>
        <el-button type="primary" @click="uploadFile">确 定</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove , getFile} from "@/api/merchant/camiloinventory";
  import {mapGetters} from "vuex";
  import {getToken} from '@/util/auth';
  let token = getToken()
  export default {
    data() {
      return {
        header:{
          'Blade-Auth':token
        },
        fileList:[],
        box:false,
        form: {},
        formChild:{},
        activityForm:{
          merchantProductId:"",
          price:"",
        },
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          index:true,
          indexLabel:"序号", 
          border: true,
          viewBtn: true,
          dialogClickModal: false,
          searchLabelWidth:120,
          align:"center",
          labelWidth:140,
          column: [
            {
              label: "入库批次",
              prop: "batchId",
              search:true,
              rules: [{
                required: true,
                message: "请输入入库批次",
                trigger: "blur"
              }]
            },
            {
              label: "出库批次",
              prop: "outboundBatchId",
              search:true,
              rules: [{
                required: true,
                message: "请输入出库批次",
                trigger: "blur"
              }]
            },
            {
              label: "商户",
              prop: "merchantId",
              type:"select",
              hide:true,
              display:false,
              filterable:true,
              dicUrl:"/api/merchant-bmg/merchant/list?current=1&size=100",
              dicMethod:'get',
              props:{
                label:"merchantName",
                value:"id",
                res:"data.records"
              },
              cascaderItem:["merchantProductId"],
              search:true,
              rules: [{
                required: true,
                message: "请输入商户",
                trigger: "blur"
              }]
            },
            {
              label: "商户名称",
              prop: "merchantName",
              rules: [{
                required: true,
                message: "请输入商户名称",
                trigger: "blur"
              }]
            },
            {
              label: "商户商品",
              prop: "merchantProductId",
              search:true,
              type:"select",
              hide:true,
              display:false,
              filterable:true,
              dicUrl:`/api/merchant-bmg/product/list?current=1&size=100&merchantId={{key}}`,
              dicMethod:'get',
              // dicQuery:{
              //   current:1,
              //   size:100,
              //   merchantId:`${key}`
              // },
              props:{
                label:"productName",
                value:"id",
                res:"data.records"
              },
              rules: [{
                required: true,
                message: "请输入商户商品",
                trigger: "blur"
              }]
            },
            {
              label: "商户商品名称",
              prop: "merchantProductName",
              minWidth:100,
              rules: [{
                required: true,
                message: "请输入商户商品名称",
                trigger: "blur"
              }]
            },
            {
              label: "商户产品号",
              prop: "merchantProductNo",
              minWidth:90,
              hide:true,
              display:false,
              rules: [{
                required: true,
                message: "请输入商户产品号",
                trigger: "blur"
              }]
            },
            {
              label: "采购成本",
              prop: "costValue",
              rules: [{
                required: true,
                message: "请输入采购成本",
                trigger: "blur"
              }]
            },
            {
              label: "卡号",
              prop: "cardNo",
              hide:true,
              rules: [{
                required: true,
                message: "请输入卡号",
                trigger: "blur"
              }]
            },
            {
              label: "卡密",
              prop: "cardCode",
              hide:true,
              rules: [{
                required: true,
                message: "请输入卡密",
                trigger: "blur"
              }]
            },
            {
              label: "有效期开始时间",
              prop: "availbleDate",
              type:"datetime",
              minWidth:180,
              valueFormat:"yyyy-MM-dd HH:mm:ss",
              rules: [{
                required: true,
                message: "请输入有效期开始时间",
                trigger: "blur"
              }]
            },
            {
              label: "有效期结束时间",
              prop: "expireDate",
              type:"datetime",
              minWidth:180,
              valueFormat:"yyyy-MM-dd HH:mm:ss",
              rules: [{
                required: true,
                message: "请输入有效期结束时间",
                trigger: "blur"
              }]
            },
            {
              label: "有效期结束时间",
              prop: "expireDateList",
              search:true,
              searchSpan:12,
              searchRange:true,
              hide:true,
              display:false,
              type:"datetime",
              minWidth:180,
              valueFormat:"yyyy-MM-dd HH:mm:ss"
            },
            {
              label: "状态",
              prop: "camiloStatus",
              search:true,
              type:"select",
              dicUrl:"/api/blade-system/dict-biz/dictionary?code=MERCHANT_CAMILO_STATUS",
              dicMethod:'get',
              props:{
                label:"dictValue",
                value:"dictKey"
              },
              rules: [{
                required: true,
                message: "请选择状态",
                trigger: "blur"
              }]
            },
            {
              label: "出库人",
              prop: "outStoreUser",
              hide:true,
              rules: [{
                required: true,
                message: "请输入出库人",
                trigger: "blur"
              }]
            },
            {
              label: "领取订单",
              prop: "orderId",
              hide:true,
              rules: [{
                required: true,
                message: "请输入领取订单",
                trigger: "blur"
              }]
            },
            {
              label: "业务方",
              prop: "businessSide",
              hide:true,
              type:"select",
              dicUrl:"/api/blade-system/dict-biz/dictionary?code=MERCHANT_BIZ_TYPE",
              dicMethod:'get',
              props:{
                label:"dictValue",
                value:"dictKey"
              },
              rules: [{
                required: true,
                message: "请选择业务方",
                trigger: "blur"
              }]
            },
            {
              label: "领取时间",
              prop: "receiveTime",
              type:"datetime",
              minWidth:180,
              valueFormat:"yyyy-MM-dd HH:mm:ss",
              rules: [{
                required: true,
                message: "请输入领取时间",
                trigger: "blur"
              }]
            },
          ]
        },
        optionChild:{
          menuBtn:false,
          labelWidth:120,
          column:[
            {
              label: "商户",
              prop: "merchantId",
              type:"select",
              hide:true,
              //editDisplay:false,
              editDisabled:true,
              filterable:true,
              dicUrl:"/api/merchant-bmg/merchant/list?current=1&size=100&merchantStatus=OPEN",
              dicMethod:'get',
              props:{
                label:"merchantName",
                value:"id",
                res:"data.records"
              },
              cascaderItem:["merchantProductId"],
              rules: [{
                required: true,
                message: "请输入商户",
                trigger: "blur"
              }]
            },
            {
              label: "商户商品",
              prop: "merchantProductId",
              type:"select",
              hide:true,
              //editDisplay:false,
              editDisabled:true,
              filterable:true,
              dicUrl:`/api/merchant-bmg/product/list?current=1&size=100&inventoryType=CAMILO&productStatus=ON&merchantId={{key}}`,
              dicMethod:'get',
              props:{
                label:"productName",
                value:"id",
                res:"data.records"
              },
              rules: [{
                required: true,
                message: "请输入商户商品",
                trigger: "blur"
              }]
            },
            {
              label: "价格（单价）",
              prop: "price",
              type:"number",
              precision:2,
              minRows:0,
              rules: [{
                required: true,
                message: "请输入单价",
                trigger: "blur"
              }]
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.camiloinventory_add, false),
          viewBtn: this.vaildData(this.permission.camiloinventory_view, true),
          delBtn: this.vaildData(this.permission.camiloinventory_delete, false),
          editBtn: this.vaildData(this.permission.camiloinventory_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        // this.onLoad(this.page);
      },
      searchChange(params, done) {
        if(params.expireDateList){
          params.expireDateStart = params.expireDateList[0]
          params.expireDateEnd = params.expireDateList[1]
          delete params.expireDateList
        }
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
      importExcel(){
        this.box = true;
      },
      dialogClose(){
        this.$refs.uploadForm.resetForm();
        this.box = false;
      },
      fileChange(file,fileList){
        this.fileList = fileList;
      },
      handleRemove(file,fileList){
        this.fileList = fileList;
      },
      uploadFile(){
        this.activityForm.merchantProductId = this.formChild.merchantProductId;
        this.activityForm.price = this.formChild.price;
        if(!this.activityForm.merchantProductId){
          this.$message.error("必须选择商品");
          return;
        }else if(!this.activityForm.price){
          this.$message.error("必须输入价格");
          return;
        }else if(this.fileList.length==0){
          this.$message.error("请选择需要上传的文件");
          return;
        }
        this.$refs.upload.submit() 
      },
      // 上传成功
      uploadSuccess(response) {
        if (response.code == 200) {
          this.$message.success("文件导入成功");
          this.$refs.uploadForm.resetForm();
          this.$refs.upload.clearFiles();
          this.box = false;
        } else {
          this.$message.error(response.msg);
        }
      },
      // 上传失败
      uploaderror(err) {
        let error = JSON.parse(err.message)
        if (err.code == "001") {
          this.$message.error("获取参数出错，请重新上传文件");
        } else {
          this.$message.error(error.msg);
        }
      },
      downloadFile(){
        getFile().then((res)=>{
          var blob = new Blob([res.data]); //创建一个blob对象
          var a = document.createElement('a'); //创建一个<a></a>标签
          a.href = URL.createObjectURL(blob); // response is a blob
          a.download = "卡密导入模板.xlsx";  //文件名称
          a.style.display = 'none';
          document.body.appendChild(a);
          a.click();
          a.remove();
        })
      }
    }
  };
</script>

<style>
</style>
